import React, { createRef, forwardRef, PureComponent } from 'react'
import {
 Button, message, Modal, Spin, Tabs,
} from 'antd'
import { connect } from '@umijs/max'
import { CreateDiffEditor } from '@/components'
import EmptyPic from '@/assets/images/empty.png'
import styles from './index.less'

const { TabPane } = Tabs

const resRawId = `${Math.random()}`

class TestModal extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      modalVisible: false,
      testLoading: false,
      restData: '',
      reqLog: [],
      activeKey: '1',
    }
    this.resRawRef = createRef()
    this.logRef = createRef()
    this.timeOut = null
  }

  toggleModal = (logId) => {
    const { modalVisible } = this.state

    if (modalVisible) {
      clearTimeout(this.timeOut)
      this.setState({
        testLoading: false,
        restData: '',
        reqLog: [],
        activeKey: '1',
      })
    }

    this.setState((prevState) => ({
      modalVisible: !prevState.modalVisible,
    }), () => {
      this.state.modalVisible && this.getLogFn(logId, 0)
    })
  }

  getLogFn = (logId, offset) => {
    const { reqLog } = this.state
    this.setState({
      testLoading: true,
    })
    this.props.dispatch({
      type: 'registerApiCreate/queryLog',
      params: {
        logId,
        offset,
      },
      cb: (res) => {
        const { status, msg, data } = res
        if (status === 200) {
          this.setState(
            {
              reqLog: reqLog.concat(data?.logContent),
            },
            () => {
              // 滚动到底部
              this.logRef.current
              && (this.logRef.current.scrollTop = this.logRef.current.scrollHeight)
            },
          )

          if (!data.logEnd) {
            // 如果没有结束，每1000毫秒递归调用
            this.timeOut = setTimeout(() => {
              this.getLog(logId, data?.offset)
            }, 1000)
          } else {
            this.setState({
              testLoading: false,
              restData:
                typeof data?.result === 'string'
                  ? data?.result
                  : JSON.stringify(data.result),
            })
          }
        } else {
          this.setState({
            testLoading: false,
          })
          message.error(msg || '服务端错误')
        }
      },
    })
  }

  callback = (key) => {
    this.setState({
      activeKey: key,
    })
  }

  render() {
    const {
      modalVisible, testLoading, restData, reqLog, activeKey,
    } = this.state

    return (
      <Modal
        className={styles.test_modal}
        title="测试运行"
        visible={modalVisible}
        maskClosable={false}
        bodyStyle={{
          height: `${document.documentElement.clientHeight * 0.65}px`,
          overflowY: 'auto',
        }}
        width={620}
        footer={[
          <Button key={1} onClick={this.toggleModal}>取消</Button>,
          // <Button key={2} loading={testLoading} onClick={this.handleTest} type="primary">开始测试</Button>,
        ]}
        onCancel={this.toggleModal}
      >
        <div className={styles.container}>
          <div className={styles.container_right}>
            <Tabs onChange={this.callback} activeKey={activeKey} type="card">
              <TabPane tab="返回结果" key="1">
                <div className={styles.json_diff_editor}>
                  <Spin spinning={testLoading}>
                    {
                      restData ? (
                        <CreateDiffEditor
                          readOnly
                          restData={restData || ''}
                          ref={this.resRawRef}
                          language="json"
                          theme="vs"
                          editorId={resRawId}
                        />
                      ) : (
                        <div className={styles.empty_box}>
                          <img src={EmptyPic} alt="" />
                          <p className={styles.note}>暂无返回结果</p>
                        </div>
                      )
                    }
                  </Spin>
                </div>
              </TabPane>
              <TabPane tab="运行日志" key="2">
                <Spin spinning={testLoading}>
                  {
                  reqLog?.length > 0 ? (
                    <div
                      className={styles.req_log_content}
                      ref={this.logRef}
                      style={{ height: '100%' }}
                    >
                      {reqLog?.join('\n')}
                    </div>
                  ) : (
                    <div className={styles.empty_box}>
                      <img src={EmptyPic} alt="" />
                      <p className={styles.note}>暂无运行日志</p>
                    </div>
                  )
                }
                </Spin>
              </TabPane>
            </Tabs>
          </div>
        </div>

      </Modal>
    )
  }
}

class WrappedComponentRef extends PureComponent {
  render() {
    const { forwardedRef, ...rest } = this.props
    return (
      <TestModal ref={forwardedRef} {...rest} />
    )
  }
}

const IComponent = connect(({ registerApiCreate }) => ({ ...registerApiCreate }))(WrappedComponentRef)

export default forwardRef((props, ref) => <IComponent {...props} forwardedRef={ref} />)
